package cat

import (
	"sync"
	"wzgames/internal/gvalidator"
	"wzgames/internal/model/user"
	"wzgames/pkg/actor/actor"
	"wzgames/pkg/actor/actorservice"
	"wzgames/pkg/logger"
	"wzgames/pkg/utils/dateutil"
)

var (
	catGuard *CatGuard
	once     sync.Once
)

type CatGuard struct {
	actorservice.ServiceMeta
}

func Actor() actorservice.IService {
	if catGuard == nil {
		once.Do(func() {
			catGuard = &CatGuard{}
			catGuard.Name = "actor_cat_guard"
		})
	}
	return catGuard
}

// OnReceive 处理用户的登录和游戏登录日志
func (c *CatGuard) OnReceive(ctx actor.Context) {
	switch m := ctx.Message().(type) {
	case UserLogin:
		c.doUserLogin(m)
	case WsLogin:
		c.doWsLogin(m)
	default:
	}
}

func (c *CatGuard) OnStart(as *actorservice.ActorService) {
	Init()
}

func (c *CatGuard) Attach(a interface{}) {
}

func (c *CatGuard) doUserLogin(data UserLogin) {
	defer logger.Recover()
	ent := &user.UserLoginEntity{
		Uid:      data.Uid,
		NodeId:   data.NodeId,
		Ip:       gvalidator.IpToBinary(data.ClientIP),
		Dateline: dateutil.UTC(),
		Uname:    data.Info.AgtUsername,
		AgtId:    data.Info.AgtID,
		Agtuid:   data.Info.AgtUserId,
	}
	passport.CreateUserLogin(ent)
}

func (c *CatGuard) doWsLogin(data WsLogin) {
	defer logger.Recover()
	ent := &user.UserGameLoginEntity{
		Uid:        data.Info.Uid,
		InstId:     data.InstId,
		NodeId:     data.NodeId,
		CurrId:     data.CurrId,
		GameId:     data.GameId,
		Ip:         gvalidator.IpToBinary(data.ClientIP),
		Dateline:   dateutil.UTC(),
		Uname:      data.Info.Uname,
		AgtId:      data.Info.AgtId,
		Agtuid:     data.Info.AgtUid,
		DeviceType: gvalidator.DeviceType(data.DeviceType),
		DeviceInfo: data.DeviceInfo,
	}
	passport.CreateUserGameLogin(ent)
}

func (c *CatGuard) OnDestroy() {
	actorservice.Stop(c.GetPID())
}
